<template>
  <div class="orders-container">
    <div class="orders-layout">
      <!-- 左侧导航栏 -->
      <div class="sidebar">
        <div
          class="sidebar-item"
          :class="{ active: activeOrderType === 'pending' }"
          @click="activeOrderType = 'pending'"
        >
          <span class="sidebar-icon">
            📋
          </span>
          <span class="sidebar-text">待付款订单</span>
        </div>
        <div
          class="sidebar-item"
          :class="{ active: activeOrderType === 'completed' }"
          @click="activeOrderType = 'completed'"
        >
          <span class="sidebar-icon">
            ✅
          </span>
          <span class="sidebar-text">已完成订单</span>
        </div>
      </div>

      <!-- 主内容区域 -->
      <div class="main-content">
        <div class="filter-bar">
          <div class="search-container">
            <el-date-picker
              v-model="dateQuery"
              type="date"
              placeholder="下单日期"
              value-format="YYYY-MM-DD"
              style="width: 120px; margin-right: 8px;"
            />
            <el-input
              v-model="movieTitleSearch"
              placeholder="电影名称"
              clearable
              style="width: 150px; margin-right: 8px;"
            />
            <button @click="applySearch" class="search-btn">搜索</button>
            <button @click="resetSearch" class="reset-btn">重置</button>
          </div>
        </div>

        <div v-if="loading" class="loading">
          <p>加载中...</p>
        </div>

        <div v-else-if="(activeOrderType === 'pending' && pendingOrders.length === 0) ||
                     (activeOrderType === 'completed' && completedOrders.length === 0)" class="no-orders">
          <el-empty :description="getEmptyDescription()">
            <el-button type="primary" @click="goToHome" class="pure-btn">去首页看看</el-button>
          </el-empty>
        </div>

        <div v-else class="orders-list">
          <!-- 待付款订单 -->
          <div v-if="activeOrderType === 'pending'">
            <!-- 待付款订单控制区 -->
            <div class="section-controls">
              <div class="select-all-container">
                <div class="left-section">
                  <div class="select-all-checkbox">
                    <input
                      type="checkbox"
                      id="select-all"
                      :checked="isAllSelected"
                      @change="toggleSelectAll"
                    />
                    <label for="select-all">全选</label>
                  </div>
                  <div class="selected-count" v-if="selectedOrderIds.length > 0">
                    已选择 {{ selectedOrderIds.length }} 个订单
                  </div>
                </div>

                <div class="right-section" v-if="selectedOrderIds.length > 0">
                  <!-- 无论选中几个订单，都显示订单统计信息和批量操作按钮 -->
                  <div class="order-summary-inline">
                    <span class="total-items-count">共 {{ getSelectedItemsCount() }} 件商品</span>
                    <span class="total-amount">总计: ¥{{ (getSelectedOrdersAmount() || 0).toFixed(2) }}</span>
                  </div>

                  <div class="batch-buttons">
                    <button @click="batchCancelOrders" class="batch-delete-btn">
                      批量取消
                    </button>
                    <button @click="batchPayOrders" class="batch-pay-btn">
                      批量支付
                    </button>
                  </div>
                </div>
              </div>
            </div>

            <!-- 待付款订单列表 -->
            <div class="orders-section">
              <div class="orders-grid">
                <div v-for="order in pendingOrders" :key="order.id" class="order-card">
                  <div class="order-header">
                    <div class="order-checkbox">
                      <input
                        type="checkbox"
                        :checked="selectedOrderIds.includes(order.id)"
                        @change="toggleOrderSelection(order.id)"
                      />
                    </div>
                    <div class="order-info">
                      <p class="order-number">订单号: {{ order.orderNumber }}</p>
                      <p class="order-date">下单时间: {{ formatDate(order.orderTime) }}</p>
                    </div>
                  </div>

                  <div class="order-items">
                    <div class="order-item">
                      <div class="item-details">
                        <h3>{{ order.movie?.title || '未知电影' }}</h3>
                        <p class="movie-info">{{ order.showtime?.hallName || '未知影厅' }} | {{ formatShowtime(order.showtime?.showTime) }}</p>
                        <p class="seat-info">座位: {{ order.seatInfo || '未知座位' }}</p>
                        <div class="quantity-price">
                          <span>单价: ¥{{ (order.showtime?.price || order.price || 0).toFixed(2) }}</span>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div class="order-footer">
                    <div class="order-total">
                      总计: ¥{{ (order.price || 0).toFixed(2) }}
                    </div>
                    <div class="order-actions">
                      <button @click="cancelOrder(order.id)" class="view-btn">
                        取消订单
                      </button>
                      <button @click="payOrder(order.id)" class="pay-btn">
                        去支付
                      </button>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 分页组件 -->
              <div class="pagination-container">
                <el-pagination
                  v-if="pendingTotal > 0"
                  background
                  layout="prev, pager, next, jumper"
                  :total="pendingTotal"
                  :page-size="pageSize"
                  :current-page="pendingCurrentPage"
                  @current-change="handlePendingPageChange"
                />
              </div>
            </div>
          </div>

          <!-- 已完成订单 -->
          <div v-if="activeOrderType === 'completed'">
            <!-- 已完成订单控制区 -->

            <!-- 已完成订单列表 -->
            <div class="orders-section">
              <div class="orders-grid">
                <div v-for="order in completedOrders" :key="order.id" class="order-card">
                  <div class="order-header">
                    <div class="order-info">
                      <p class="order-number">订单号: {{ order.orderNumber }}</p>
                      <p class="order-date">下单时间: {{ formatDate(order.orderTime) }}</p>
                    </div>
                  </div>

                  <div class="order-items">
                    <div class="order-item">
                      <div class="item-details">
                        <h3>{{ order.movie?.title || '未知电影' }}</h3>
                        <p class="movie-info">{{ order.showtime?.hallName || '未知影厅' }} | {{ formatShowtime(order.showtime?.showTime) }}</p>
                        <p class="seat-info">座位: {{ order.seatInfo || '未知座位' }}</p>
                        <div class="quantity-price">
                          <span>单价: ¥{{ (order.showtime?.price || order.price || 0).toFixed(2) }}</span>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div class="order-footer">
                    <div class="order-total">
                      总计: ¥{{ (order.price || 0).toFixed(2) }}
                    </div>
                    <div class="order-actions">
                      <!-- 已移除查看详情按钮 -->
                    </div>
                  </div>
                </div>
              </div>

              <!-- 分页组件 -->
              <div class="pagination-container">
                <el-pagination
                  v-if="completedTotal > 0"
                  background
                  layout="prev, pager, next, jumper"
                  :total="completedTotal"
                  :page-size="pageSize"
                  :current-page="completedCurrentPage"
                  @current-change="handleCompletedPageChange"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElDatePicker, ElInput } from 'element-plus'
import { useUserStore } from '../store/user'
// import { useCartStore } from '../store/cart'
import { useWalletStore } from '../store/wallet'
import axiosInstance from '../utils/axiosInstance'

// 定义 Order 接口
// 不再需要OrderItem接口，因为电影订单不包含多个项目

interface Order {
  id: number;
  orderNumber?: string;
  orderTime: string; // 后端使用orderTime而不是orderDate
  status: string | number;
  price: number; // 后端使用price而不是totalAmount
  seatInfo?: string; // 座位信息
  movieId?: number;
  showtimeId?: number;
  // 关联信息
  movie?: {
    id: number;
    title: string;
    director?: string;
    duration?: number;
  };
  showtime?: {
    id: number;
    hallName: string;
    showTime: string;
    price: number;
  };
  user?: any;
}

const router = useRouter()
const userStore = useUserStore()
// const cartStore = useCartStore()
const walletStore = useWalletStore()

const orders = ref<Order[]>([])
const loading = ref(false)
// 移除图书相关的搜索条件
// const bookTitleQuery = ref('')
// const authorQuery = ref('')
const dateQuery = ref('') // 保留日期查询
const movieTitleSearch = ref('') // 新增：电影名称搜索
const newOrderCreated = ref(false)
// 当前选中的订单类型：'pending'表示待付款订单，'completed'表示已完成订单
const activeOrderType = ref('pending')
// 选中的订单ID列表
const selectedOrderIds = ref<number[]>([])
// 是否全选
const isAllSelected = ref(false)

// 分页相关
const pageSize = ref(9) // 每页显示9个订单
const pendingCurrentPage = ref(1)
const completedCurrentPage = ref(1)
const pendingTotal = ref(0)
const completedTotal = ref(0)

// 获取用户信息
const userId = computed(() => userStore.getUserId)

// !!! 移除 watch 语句，稍后将其移到 setup 末尾 !!!

// --- 修改 onMounted 钩子 (移除加载相关逻辑) ---
onMounted(() => {
  // 只保留登录检查逻辑
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录查看订单');
    router.push('/login');
  }
  // !!! 移除 onMounted 中的 loadOrders 调用 !!!
});
// --- 结束修改 onMounted 钩子 ---

// 筛选订单的通用函数 (简化)
const filterOrdersByQueries = (orders: Order[]) => {
  return orders.filter(order => {
    // 如果没有任何搜索条件，返回所有订单
    if (!dateQuery.value && !movieTitleSearch.value) { // 检查日期和电影名称
      return true
    }

    // 检查日期
    if (dateQuery.value) {
      try {
        const orderDate = new Date(order.orderTime).toISOString().split('T')[0]
        if (orderDate !== dateQuery.value) {
          return false
        }
      } catch (error) {
        console.error('日期格式转换错误:', error)
        // 如果日期转换出错，不进行日期筛选
      }
    }

    // 检查电影名称
    if (movieTitleSearch.value && !(order.movie?.title?.toLowerCase().includes(movieTitleSearch.value.toLowerCase()))) {
        return false;
    }

    return true
  })
}

// 获取待付款订单
const pendingOrders = computed(() => {
  const pending = orders.value.filter(order => order.status === 0)
  return filterOrdersByQueries(pending)
})

// 获取已完成订单
const completedOrders = computed(() => {
  const completed = orders.value.filter(order => isCompletedOrder(order.status))
  return filterOrdersByQueries(completed)
})

// 获取其他状态订单 (暂未使用)
// const otherOrders = computed(() => {
//   const other = orders.value.filter(order =>
//     !isCompletedOrder(order.status) && order.status !== 0 && order.status !== 2
//   )
//   return filterOrdersByQueries(other)
// })

// 计算所有订单的总数 (用于调试)
// const totalOrdersCount = computed(() => {
//   return pendingOrders.value.length + shippedOrders.value.length + completedOrders.value.length
// })

// 计算待付款订单的总商品数量
const totalPendingItemsCount = computed(() => {
  return pendingOrders.value.reduce((total, order) => {
    return total + getTotalItems(order)
  }, 0)
})

// 计算待付款订单的总价格
const totalPendingOrdersAmount = computed(() => {
  return pendingOrders.value.reduce((total, order) => {
    return total + (order.price || 0)
  }, 0)
})

// 已移除全选相关的计算属性

const formatDate = (dateString: string) => {
  if (!dateString) return '未知时间';
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    console.error('日期格式化错误:', error);
    return '日期格式错误';
  }
}

// 格式化场次时间
const formatShowtime = (dateString: string | undefined) => {
  if (!dateString) return '未知时间';
  try {
    const date = new Date(dateString);
    // 获取月日
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    // 获取时分
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${month}-${day} ${hours}:${minutes}`;
  } catch (error) {
    console.error('场次时间格式化错误:', error);
    return '时间格式错误';
  }
}

const getStatusText = (status: any): string => {
  // 如果是数字，则按照后端的状态码处理
  if (typeof status === 'number') {
    const statusMap: { [key: number]: string } = {
      0: '待付款',
      1: '已完成'
      // 已取消的订单直接删除，不再显示
    }
    return statusMap[status] || `未知状态(${status})`
  }

  // 兼容字符串状态
  const statusMap: { [key: string]: string } = {
    'pending': '待付款',
    'completed': '已完成'
    // 已取消的订单直接删除，不再显示
  }
  return statusMap[status] || status
}

// 获取状态对应的CSS类名
const getStatusClass = (status: any): string => {
  // 如果是数字，则按照后端的状态码处理
  if (typeof status === 'number') {
    const statusClassMap: { [key: number]: string } = {
      0: 'pending',
      1: 'completed' // 状态码1对应已完成样式
      // 已取消的订单直接删除，不再显示
    }
    return statusClassMap[status] || ''
  }

  // 如果是字符串，直接返回
  return status
}

// 判断订单是否已完成
const isCompletedOrder = (status: any): boolean => {
  // 如果是数字状态码
  if (typeof status === 'number') {
    // 只有状态码1表示已完成
    return status === 1
  }

  // 如果是字符串状态
  return status === 'completed'
}

// 判断订单是否有效（只有待支付和已完成的订单是有效的）
const isValidOrder = (status: any): boolean => {
  if (typeof status === 'number') {
    // 只有状态码0（待支付）和1（已完成）是有效的
    return status === 0 || status === 1
  }

  // 如果是字符串状态
  return status === 'pending' || status === 'completed'
}

// 获取订单中的电影标题
const getMovieTitle = (order: Order): string => {
  return order.movie?.title || '未知电影'
}

// 获取订单中的影厅名称
const getHallName = (order: Order): string => {
  return order.showtime?.hallName || '未知影厅'
}

// 获取订单中的座位信息
const getSeatInfo = (order: Order): string => {
  return order.seatInfo || '未知座位'
}

// 获取订单价格
const getOrderPrice = (order: Order): number => {
  return order.price || 0
}

// 由于电影票订单通常只有一张票，所以总数量为1
const getTotalItems = (order: Order): number => {
  return 1
}

// 处理中订单相关功能已移除

// 跳转到首页
const goToHome = () => {
  router.push('/home')
}

// 获取空订单提示文本
const getEmptyDescription = () => {
  if (activeOrderType.value === 'pending') {
    return '暂无待付款订单'
  } else {
    return '暂无已完成订单'
  }
}

const payOrder = async (orderId: number) => {
  const orderToPay = pendingOrders.value.find(o => o.id === orderId);
  if (!orderToPay) {
    ElMessage.error('找不到订单信息');
    return;
  }

  const totalAmount = orderToPay.price || 0;

  try {
    // 检查钱包余额
    await walletStore.fetchBalance();
    if (walletStore.balance < totalAmount) {
      ElMessage.error('余额不足，请先充值');
      return;
    }

    await ElMessageBox.confirm(
      `您确定要支付订单 ${orderToPay.orderNumber} 吗？金额: ¥${totalAmount.toFixed(2)}`,
      '支付确认',
      {
        confirmButtonText: '确定支付',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    // 调用后端支付接口
    const response = await axiosInstance.post(`/orders/${orderId}/pay`);

    if (response.data.success) {
      ElMessage.success('支付成功');
      // 更新钱包余额显示
      walletStore.decreaseBalance(totalAmount);
      // 刷新订单列表
      fetchPendingOrders();
      fetchCompletedOrders();
      // 如果有选中，也需要更新
      if (selectedOrderIds.value.includes(orderId)) {
        selectedOrderIds.value = selectedOrderIds.value.filter(id => id !== orderId);
      }
    } else {
      ElMessage.error(response.data.message || '支付失败');
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('支付订单错误:', error);
      ElMessage.error(error.response?.data?.message || '支付时发生错误');
    }
  }
};

// 取消订单
const cancelOrder = async (orderId: number) => {
  const orderToCancel = pendingOrders.value.find(o => o.id === orderId);
  if (!orderToCancel) {
    ElMessage.error('找不到订单信息');
    return;
  }

  try {
    await ElMessageBox.confirm(
      `您确定要取消订单 ${orderToCancel.orderNumber} 吗？`,
      '取消订单确认',
      {
        confirmButtonText: '确定取消',
        cancelButtonText: '再想想',
        type: 'warning',
      }
    );

    // 调用后端取消接口
    const response = await axiosInstance.put(`/orders/${orderId}/cancel`); // 使用 PUT 方法与后端接口匹配

    if (response.data.success) {
      ElMessage.success('订单取消成功');

      // 从购物车移除对应商品 (如果需要且 cartStore 存在)
      // orderToCancel.orderItems?.forEach(item => {
      //   // cartStore.removeBatch(item.bookId, item.quantity);
      // });

      // 刷新订单列表
      loadOrders(); // <--- 刷新列表
      // 如果有选中，也需要更新
      if (selectedOrderIds.value.includes(orderId)) {
        selectedOrderIds.value = selectedOrderIds.value.filter(id => id !== orderId);
      }
    } else {
      ElMessage.error(response.data.message || '取消订单失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单错误:', error);
      ElMessage.error('取消订单时发生错误');
    }
  }
};

// 查看订单详情功能已移除

// 切换单个订单的选择状态
const toggleOrderSelection = (orderId: number) => {
  const index = selectedOrderIds.value.indexOf(orderId)
  if (index === -1) {
    // 如果不在选中列表中，添加
    selectedOrderIds.value.push(orderId)
  } else {
    // 如果已在选中列表中，移除
    selectedOrderIds.value.splice(index, 1)
  }

  // 更新全选状态
  updateSelectAllState()
}

// 更新全选状态
const updateSelectAllState = () => {
  isAllSelected.value = pendingOrders.value.length > 0 &&
    selectedOrderIds.value.length === pendingOrders.value.length
}

// 切换全选/取消全选
const toggleSelectAll = () => {
  if (isAllSelected.value) {
    // 如果当前是全选状态，则取消全选
    selectedOrderIds.value = []
  } else {
    // 如果当前不是全选状态，则全选
    selectedOrderIds.value = pendingOrders.value.map(order => order.id)
  }
  isAllSelected.value = !isAllSelected.value
}

// 批量取消订单
const batchCancelOrders = async () => {
  if (selectedOrderIds.value.length === 0) {
    ElMessage.warning('请先选择要取消的订单');
    return;
  }

  try {
    await ElMessageBox.confirm(
      `您确定要取消选中的 ${selectedOrderIds.value.length} 个订单吗？此操作不可恢复。`,
      '批量取消确认',
      {
        confirmButtonText: '确定取消',
        cancelButtonText: '再想想',
        type: 'warning',
      }
    );

    // 调用后端批量取消接口
    const response = await axiosInstance.post('/orders/batch-cancel', { orderIds: selectedOrderIds.value }); // 使用 axiosInstance 和相对路径

    if (response.data.success) {
      ElMessage.success('批量取消成功');

      // 从购物车移除对应商品 (如果需要且 cartStore 存在)
      // const ordersToCancel = pendingOrders.value.filter(order => selectedOrderIds.value.includes(order.id));
      // ordersToCancel.forEach(order => {
      //   order.orderItems?.forEach(item => {
      //     // cartStore.removeBatch(item.bookId, item.quantity); // 假设有批量移除方法
      //   });
      // });

      // 清空选中并刷新列表
      selectedOrderIds.value = [];
      loadOrders(); // <--- 刷新列表
    } else {
      ElMessage.error(response.data.message || '批量取消失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量取消错误:', error);
      ElMessage.error('批量取消时发生错误');
    }
  }
};

// 批量支付订单
const batchPayOrders = async () => {
  if (selectedOrderIds.value.length === 0) {
    ElMessage.warning('请先选择要支付的订单');
    return;
  }

  const totalAmount = getSelectedOrdersAmount();

  try {
    // 检查钱包余额
    await walletStore.fetchBalance();
    if (walletStore.balance < totalAmount) {
      ElMessage.error('余额不足，请先充值');
      return;
    }

    await ElMessageBox.confirm(
      `您确定要支付选中的 ${selectedOrderIds.value.length} 个订单吗？总金额: ¥${totalAmount.toFixed(2)}`,
      '批量支付确认',
      {
        confirmButtonText: '确定支付',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    // 调用后端批量支付接口
    const response = await axiosInstance.post('/orders/batch-pay', { orderIds: selectedOrderIds.value });

    if (response.data.success) {
      ElMessage.success('批量支付成功');
      // 更新钱包余额显示
      walletStore.decreaseBalance(totalAmount);
      // 清空选中并刷新列表
      selectedOrderIds.value = [];
      fetchPendingOrders();
      fetchCompletedOrders();
    } else {
      ElMessage.error(response.data.message || '批量支付失败');
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('批量支付错误:', error);
      ElMessage.error(error.response?.data?.message || '批量支付时发生错误');
    }
  }
};

// 获取选中订单的商品总数
const getSelectedItemsCount = () => {
  const selectedOrders = pendingOrders.value.filter(order =>
    selectedOrderIds.value.includes(order.id)
  )

  return selectedOrders.reduce((total, order) => {
    return total + getTotalItems(order)
  }, 0)
}

// 获取选中订单的总金额
const getSelectedOrdersAmount = () => {
  const selectedOrders = pendingOrders.value.filter(order =>
    selectedOrderIds.value.includes(order.id)
  )

  return selectedOrders.reduce((total, order) => {
    return total + (order.price || 0)
  }, 0)
}

// 监听订单列表变化，更新选择状态
watch(() => pendingOrders.value, () => {
  // 移除已不存在的订单ID
  selectedOrderIds.value = selectedOrderIds.value.filter(id =>
    pendingOrders.value.some(order => order.id === id)
  )
  // 更新全选状态
  updateSelectAllState()
}, { deep: true })

// 处理待付款订单页码变化
const handlePendingPageChange = (page: number) => {
  pendingCurrentPage.value = page;
  loadOrders(); // <--- 调用 loadOrders
}

// 处理已完成订单页码变化
const handleCompletedPageChange = (page: number) => {
  completedCurrentPage.value = page;
  loadOrders(); // <--- 调用 loadOrders
}

// 获取待付款订单
const fetchPendingOrders = () => {
  activeOrderType.value = 'pending';
  loadOrders();
}

// 获取已完成订单
const fetchCompletedOrders = () => {
  activeOrderType.value = 'completed';
  loadOrders();
}

// 应用搜索
const applySearch = () => {
  pendingCurrentPage.value = 1;
  completedCurrentPage.value = 1;
  loadOrders(); // <--- 调用 loadOrders
}

// 重置搜索 (简化)
const resetSearch = () => {
  // bookTitleQuery.value = ''
  // authorQuery.value = ''
  dateQuery.value = '' // 只重置日期
  movieTitleSearch.value = '' // 重置电影名称

  // 重置页码
  pendingCurrentPage.value = 1;
  completedCurrentPage.value = 1;
  loadOrders();
  ElMessage.success('搜索条件已重置');
}

// --- 新增：统一的加载订单函数 (Part A) ---
const loadOrders = async () => {
  const currentUserId = userId.value;
  if (!currentUserId) {
    console.warn('用户未登录，无法加载订单');
    orders.value = [];
    pendingTotal.value = 0;
    completedTotal.value = 0;
    loading.value = false; // 确保 loading 关闭
    return;
  }

  loading.value = true; // 开始加载

  try {
    // 1. 获取用户的所有订单 (假设API返回所有订单)
    const response = await axiosInstance.get(`/orders/user/${currentUserId}`);
    console.log('原始订单数据:', response.data);

    let allUserOrders: Order[] = [];
    if (response.data && Array.isArray(response.data)) {
      allUserOrders = response.data;
    } else if (response.data && response.data.orders && Array.isArray(response.data.orders)) {
      // 兼容可能的分页包装器
      allUserOrders = response.data.orders;
    } else {
      console.warn('后端返回的订单数据格式不正确或为空');
      allUserOrders = [];
    }

    // --- 开始添加过滤和计数逻辑 ---
    // 2. 过滤出有效状态的订单 (待支付 和 已完成)
    const validOrders = allUserOrders.filter((order: Order) => isValidOrder(order.status));

    // 3. 根据当前激活的 tab 页过滤订单
    let statusFilteredOrders: Order[];
    if (activeOrderType.value === 'pending') {
        statusFilteredOrders = validOrders.filter(o => o.status === 0);
    } else { // 'completed'
        statusFilteredOrders = validOrders.filter(o => isCompletedOrder(o.status));
    }

    // 4. 应用搜索条件
    const searchFilteredOrders = filterOrdersByQueries(statusFilteredOrders);

    // 5. 更新总数 (基于搜索过滤后的结果)
    if (activeOrderType.value === 'pending') {
      pendingTotal.value = searchFilteredOrders.length;
    } else {
      completedTotal.value = searchFilteredOrders.length;
    }

    // --- 开始添加分页逻辑 ---
    // 6. 应用分页
    let ordersToShow: Order[] = [];
    let currentPage: number;
    let totalToShow: number;

    if (activeOrderType.value === 'pending') {
      currentPage = pendingCurrentPage.value;
      totalToShow = pendingTotal.value;
    } else {
      currentPage = completedCurrentPage.value;
      totalToShow = completedTotal.value;
    }

    const maxPage = Math.ceil(totalToShow / pageSize.value) || 1;
    // 如果当前页码在过滤后超出范围，重置为最大页码
    if (currentPage > maxPage) {
        if (activeOrderType.value === 'pending') pendingCurrentPage.value = maxPage;
        else completedCurrentPage.value = maxPage;
        currentPage = maxPage; // 使用调整后的页码进行slice
    }

    const start = (currentPage - 1) * pageSize.value;
    const end = start + pageSize.value;
    ordersToShow = searchFilteredOrders.slice(start, end);

    // 7. 更新用于显示的订单列表
    orders.value = ordersToShow;
    console.log(`当前页 (${activeOrderType.value}) 订单数据:`, ordersToShow);
    // --- 结束添加分页逻辑 ---

  } catch (error) {
    // --- 修改 Catch 块 ---
    console.error(`加载 ${activeOrderType.value} 订单失败:`, error);
    orders.value = []; // 清空列表以显示空状态
    pendingTotal.value = 0;
    completedTotal.value = 0;
    ElMessage.error('加载订单数据时出错，请稍后重试');
    // --- 结束修改 Catch 块 ---
  } finally {
    // --- 修改 Finally 块 ---
    loading.value = false; // 确保加载结束
    // 加载完成后可能需要更新全选状态 (如果当前是 pending tab)
    if (activeOrderType.value === 'pending') {
        // 确保 updateSelectAllState 函数存在且逻辑正确
         if (typeof updateSelectAllState === 'function') {
            updateSelectAllState();
         } else {
            console.warn('updateSelectAllState function not found after loading orders.');
         }
    }
    // --- 结束修改 Finally 块 ---
  }
}; // <--- 确保函数在这里正确结束
// --- 结束：统一的加载订单函数 ---

// !!! 将 watch 语句添加到 setup 函数末尾 !!!
watch(userId, (newUserId) => {
  if (newUserId && userStore.isLoggedIn) {
    console.log('用户 ID 可用/已更改，正在获取订单...');
    // 重置页码并加载数据
    pendingCurrentPage.value = 1;
    completedCurrentPage.value = 1;
    loadOrders();
  } else {
    // 用户登出或初始 userId 无效
    console.log('用户登出或未登录，清空订单...');
    orders.value = [];
    pendingTotal.value = 0;
    completedTotal.value = 0;
    loading.value = false;
  }
}, { immediate: true }); // immediate: true 确保挂载时运行

// 监听 activeOrderType 变化，用于切换标签页时重新加载
watch(activeOrderType, (newType) => {
  console.log(`切换到 ${newType} 订单标签`);
  // 重置页码并加载数据
  if (newType === 'pending') {
      pendingCurrentPage.value = 1;
  } else {
      completedCurrentPage.value = 1;
  }
   // 清空选中状态
  selectedOrderIds.value = [];
  isAllSelected.value = false;
  loadOrders();
});

</script>

<style scoped>
.orders-container {
  max-width: 1800px;
  margin: 0 auto;
  padding: 20px;
  /* Remove background from container if App.vue handles it */
}

.orders-layout {
  display: flex;
  margin-top: 0;
  min-height: 600px;
  /* Make layout background transparent if needed, or slightly opaque */
  /* background-color: rgba(255, 255, 255, 0.9); /* Example: Slightly opaque white */
  border: 1px solid rgba(233, 236, 239, 0.5); /* Make border slightly transparent */
  border-radius: 8px;
  overflow: hidden;
}

.sidebar {
  width: 200px;
  /* background-color: #f5f7fa; */
  background-color: rgba(245, 247, 250, 0.85); /* Semi-transparent light grey */
  border-right: 1px solid rgba(233, 236, 239, 0.5); /* Semi-transparent border */
  padding: 20px 0;
  transition: background-color 0.3s ease;
}

.sidebar-item {
  padding: 15px 20px;
  display: flex;
  align-items: center;
  cursor: pointer;
  position: relative;
  transition: all 0.3s;
}

.sidebar-item:hover {
  background-color: rgba(233, 236, 239, 0.7); /* Semi-transparent hover */
}

.sidebar-item.active {
  /* Keep active item opaque for clarity, or make semi-transparent blue */
   background-color: rgba(64, 158, 255, 0.85); /* Semi-transparent blue */
  color: white;
}

.sidebar-icon {
  margin-right: 10px;
  font-size: 18px;
}

.sidebar-text {
  font-size: 16px;
}

.badge {
  position: absolute;
  right: 20px;
  background-color: #f56c6c;
  color: white;
  border-radius: 10px;
  padding: 2px 8px;
  font-size: 12px;
}

.sidebar-item.active .badge {
  background-color: white;
  color: #409eff;
}

.main-content {
  flex: 1;
  padding: 20px;
  /* background-color: white; */
  background-color: rgba(255, 255, 255, 0.85); /* Semi-transparent white */
  overflow-y: auto;
  min-height: 600px;
  transition: all 0.3s ease;
}

h1 {
  margin-bottom: 20px;
  color: #333;
}

.order-count {
  font-size: 16px;
  color: #909399;
  font-weight: normal;
  margin-left: 10px;
}

.filter-bar {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 20px;
  /* background-color: rgba(255, 255, 255, 0.9); /* Optional: Make filter bar semi-transparent */
  padding: 15px;
  border-radius: 4px;
  /* box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05); */ /* Optional shadow */
}

.search-container {
  display: flex;
  gap: 5px;
  width: 100%;
  align-items: center;
}

.search {
  flex: 0 0 auto;
  width: 120px;
}

.search input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  width: 100%;
}

.search-buttons {
  display: flex;
  gap: 10px;
}

.search-btn, .reset-btn {
  padding: 8px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: bold;
  margin-left: 5px;
}

.search-btn {
  background-color: #409eff;
  color: white;
}

.search-btn:hover {
  background-color: #66b1ff;
}

.reset-btn {
  background-color: #909399;
  color: white;
}

.reset-btn:hover {
  background-color: #a6a9ad;
}

.loading, .no-orders {
  text-align: center;
  padding: 40px 0;
  color: #666;
}

/* 覆盖 el-empty 组件的样式 */
.no-orders :deep(.el-empty__image) {
  height: 160px;
}

.no-orders :deep(.el-empty__description) {
  margin-top: 10px;
}

.no-orders :deep(.el-button) {
  border: none !important;
  box-shadow: none !important;
  outline: none !important;
}

.shop-now {
  display: inline-block;
  margin-top: 10px;
  text-decoration: none;
  border: none;
  outline: none;
}

.select-all-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 15px; /* 统一上下内边距 */
  /* background-color: #f8f9fa; */
  background-color: rgba(248, 249, 250, 0.85); /* Semi-transparent */
  border-radius: 4px;
  border: 1px solid rgba(233, 236, 239, 0.5); /* Semi-transparent border */
  height: 52px; /* 固定高度 */
  box-sizing: border-box;
}

.left-section {
  display: flex;
  align-items: center;
}

.right-section {
  display: flex;
  align-items: center;
}

.select-all-checkbox {
  display: flex;
  align-items: center;
  margin-right: 20px;
  height: 22px; /* 固定高度 */
}

.select-all-checkbox input[type="checkbox"] {
  width: 18px;
  height: 18px;
  margin: 0 8px 0 0;
  padding: 0;
  cursor: pointer;
}

.select-all-checkbox label {
  font-weight: bold;
  cursor: pointer;
}

.selected-count {
  margin-right: 20px;
}

.order-summary-inline {
  display: flex;
  align-items: center;
  margin-right: 20px;
}

.total-items-count {
  margin-right: 20px;
  font-weight: bold;
  color: #409EFF;
  font-size: 16px;
}

.batch-buttons {
  display: flex;
  align-items: center;
}

.order-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}

.total-amount {
  font-weight: bold;
  color: #F56C6C;
  font-size: 16px;
}

.batch-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 10px 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}

.batch-buttons {
  display: flex;
  align-items: center;
}

.selected-count {
  font-weight: bold;
  color: #606266;
}

.batch-delete-btn {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 10px;
  font-size: 14px;
}

.batch-delete-btn:hover {
  background-color: #66b1ff;
}

.batch-pay-btn {
  background-color: #67C23A;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  font-weight: bold;
  font-size: 14px;
}

.batch-pay-btn:hover {
  background-color: #85ce61;
}

.confirm-btn {
  background-color: #67C23A;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  font-weight: bold;
}

.confirm-btn:hover {
  background-color: #85ce61;
}

.order-total {
  font-weight: bold;
  color: #F56C6C;
  font-size: 16px;
}

.section-controls {
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 15px; /* 添加底部间距 */
}

.orders-section {
  margin-bottom: 30px;
  border-radius: 8px;
  overflow: hidden;
}

.section-title {
  padding: 10px 15px;
  background-color: #f5f7fa;
  border-left: 4px solid #409eff;
  margin-bottom: 15px;
  font-size: 18px;
  color: #333;
}

.orders-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.order-card {
  /* background: white; */
  background: rgba(255, 255, 255, 0.9); /* Slightly more opaque white for cards */
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  /* background-color: #f8f9fa; */
  background-color: rgba(248, 249, 250, 0.85); /* Semi-transparent */
  border-bottom: 1px solid rgba(238, 238, 238, 0.5); /* Semi-transparent border */
}

.order-checkbox {
  margin-right: 15px;
  display: flex;
  align-items: center;
  height: 22px; /* 固定高度 */
}

.order-checkbox input[type="checkbox"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
  margin: 0;
  padding: 0;
}

.order-info {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.order-number {
  font-weight: bold;
  margin: 0;
  text-align: center;
}

.order-date {
  color: #666;
  margin: 5px 0 0;
  font-size: 14px;
  text-align: center;
}

.order-status {
  padding: 6px 12px;
  border-radius: 4px;
  font-weight: bold;
}

.pending {
  background-color: #ffeeba;
  color: #856404;
}

.paid {
  background-color: #d1ecf1;
  color: #0c5460;
}

.shipped {
  background-color: #c3e6cb;
  color: #155724;
}

.delivered {
  background-color: #c3e6cb;
  color: #155724;
}

.completed {
  background-color: #b8daff;
  color: #004085;
}

.cancelled {
  background-color: #f8d7da;
  color: #721c24;
}

.order-items {
  padding: 15px;
  flex-grow: 1;
}

.order-item {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.order-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.item-details h3 {
  margin: 0 0 5px;
  font-size: 16px;
}

.movie-info, .seat-info {
  color: #666;
  margin: 0 0 5px;
  font-size: 14px;
}

.movie-info {
  color: #409EFF;
  font-weight: bold;
}

.seat-info {
  color: #67C23A;
}

.quantity-price {
  display: flex;
  justify-content: space-between;
  color: #666;
  font-size: 14px;
}

.total-price {
  font-weight: bold;
  color: #e53935;
  font-size: 16px;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  /* background-color: #f8f9fa; */
  background-color: rgba(248, 249, 250, 0.85); /* Semi-transparent */
  border-top: 1px solid rgba(238, 238, 238, 0.5); /* Semi-transparent border */
}

.order-actions {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
}

.order-actions button {
  margin: 5px;
  padding: 6px 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  white-space: nowrap;
}

.confirm-btn {
  background-color: #4caf50;
  color: white;
}

.waiting-shipment {
  color: #ff9800;
  font-size: 14px;
  padding: 6px 10px;
  border: 1px dashed #ff9800;
  border-radius: 4px;
  display: inline-block;
}

.pay-btn {
  background-color: #f44336;
  color: white;
}

.view-btn {
  background-color: #409eff;
  color: white;
}

.cancel-btn {
  background-color: #409eff;
  color: white;
}

.delete-btn {
  background-color: #409eff;
  color: white;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .orders-grid {
    grid-template-columns: 1fr;
  }

  .order-header {
    flex-direction: column;
    align-items: center;
  }

  .order-status {
    margin-top: 10px;
    align-self: flex-start;
  }

  .order-actions {
    justify-content: center;
  }
}

/* 这个样式已经在上面定义过了 */

.pure-btn {
  background-color: #409eff !important;
  color: white !important;
  border: none !important;
  border-radius: 4px !important;
  padding: 10px 20px !important;
  font-size: 16px !important;
  cursor: pointer;
  transition: background-color 0.3s;
  outline: none !important;
  box-shadow: none !important;
}

.pure-btn:hover,
.pure-btn:focus,
.pure-btn:active {
  background-color: #66b1ff !important;
  color: white !important;
  outline: none !important;
  box-shadow: none !important;
  border: none !important;
}

/* 分页容器样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 10px 0;
}
</style>